package com.example.netty.Netty启动流程;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author liupk
 * @date 2018/10/23
 */
public class NettyClient {
    
    /**最大连接重试次数*/
    private static int MAX_RETRY = 5;
    /**地址*/
    private static String HOST="127.0.0.1";
    /**端口*/
    private static int PORT = 25 ;
    
    
    public static void main(String[] args) {
        
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        bootstrap
                .group(worker)
                .channel(NioSocketChannel.class)
                /**连接超时设置*/
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,5000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                    
                    }
                });
        connect(bootstrap,HOST,PORT,MAX_RETRY);
    }
    
    private static void connect(Bootstrap bootstrap,String host,int port,int retry){
        bootstrap.connect(host,port).addListener(future -> {
           if (future.isSuccess()){
               System.out.println("连接服务器成功"+host+port);
           }else if (retry == 0){
               System.out.println("重试连接次数过多，请稍后重试");
           }else {
               /**第几次重连*/
               int order = (MAX_RETRY - retry) + 1;
               /**本地重连的间隔*/
               int delay = 1 << order;
               System.out.println(new Date() + "连接服务器失败" + host + port+"第"+delay+"次失败重连");
               bootstrap.config().group().schedule(() -> connect(bootstrap,host,port,retry - 1 ),delay, TimeUnit.SECONDS);
           }
        });
    }
}